﻿/// <reference path="../../jQuery/jquery.vsdoc.js"/>
/// <reference path="../../jQuery/jquery.autoloadselect.js"/>

//var j = jQuery.noConflict();
var currentTab = 0;
var focusItem = "#autoRole";
var personId = 0;

jQuery(function ($) {
	$("input[type='hidden']").each(function (pos) { $(this).val(0); });

	$("#nowOrThen").buttonset();
	$("input[name=nowOrThen]").click(function (evnt) {
		$("#autoProd")
			.autocomplete("option", { extraParams: { recentOnly: this.id == "recent", limit: 20} })
			.val('').focus();
	});


	$("#autoCredit").combobox();
	$("#autoAuthor").combobox();

	$("#btnInstructions").click(function () {
		$("#dialogInstructions").dialog({
			resizable: true,
			autoOpen: true,
			height: 500,
			width: 600
		});
	});

	$("#tabCastCrew").tabs().bind("tabsselect", function (event, ui) {
		currentTab = ui.index;
		LoadCrewGrid(currentTab);
		switch (ui.index) {
			case 0: // Cast
				$("#Role").show();
				$("#Credit").hide();
				focusItem = "#autoRole";
				break;

			case 1: // crew
				$("#Role").hide();
				$("#Credit").show();
				$("#autoCredit").combobox("show");
				$("#autoAuthor").combobox("hide");
				focusItem = "#autoCredit";
				break;

			case 2:     // author
				$("#Role").hide();
				$("#Credit").show();
				$("#autoCredit").combobox("hide");
				$("#autoAuthor").combobox("show");
				focusItem = "#autoAuthor";
				break;

			// if case == 4, focusItem shouldn't change.                      
		}
	});

	// ------------  PRODUCTIONS ----------------------------------
	$("#autoProd").autocomplete(
	{
		source: AutoCompleteSource,
		url: siteRoot + "/Show/ProductionsJson.rails",
		extraParams: { recentOnly: true, limit: 20 },
		cacheLength: 0,
		isJson: true,
		valueFld: 'ID',
		width: 744,
		mustMatch: false,
		formatItem: function (row, pos, num, term) {
			return "<b>" + row.Title + "</b><br /><i>" + row.Venue + '</i> (' + row.Year + ')';
		},
		formatResult: function (data, value) {
			return data.Title + ' | ' + data.Venue + ' (' + data.Year + ')';
		},
		select: function (event, data) {
			ShowProd(data.item.item.ID);
		}
	}).blur(function (evnt, data) {
		$("#autoName").setFocus();
	});

	// ------------  PERSON ----------------------------------

	$("#autoName").autocomplete({
		source: AutoCompleteSource,
		url: siteRoot + "/Person/SearchJson.rails",
		width: 500,
		mustMatch: false,
		autoFill: false,
		selectFirst: false,
		formatItem: ACformatItem,
		formatResult: ACformatResult,
		select: function (event, data) {
			if (typeof (data.item) != "undefined") {
				// called if selction from list
				var textbox = event.target.value;
				var menu = data.item.value;
				if (textbox === menu.substr(menu, textbox.length))
					personId = data.item.item.id;
			}
		}
	})
	.focus(function () {
		personId = 0;
		$(this).val("");
		if (this.menu)
			this.menu.element.remove();
	})
	.bind("blur", function () {
		$("#txtErrorMsg").html("");
		if (personId == 0) {
			var name = this.value;
			if (name && name.length > 0) {
				// create person via ajax call & get ID
				$("#imgLoading").show();
				j.getJSON(siteRoot + '/Person/CreatePerson.rails',
				{ name: name },
				function (body, status) {
					$("#imgLoading").hide();
					if (body.ID < 0) {
						$("#txtErrorMsg").html(body.Message);
					}
					else {
						$(this).val(body.Name);
						personId = body.ID;
					}
				});
			}
		}
		else {
			$("#tabBio").html('loading');
			var selected = $("#tabCastCrew").tabs("option", "selected");

			//    		$(focusItem).setFocus();
			j.getJSON(siteRoot + '/Person/BioJson.rails',
			  {
			  	id: personId
			  },
			  function (body, status) {
			  	$("#imgLoading").hide();
			  	$("#tabBio").html('Bio');
			  	var block = $('#fragment-bio');
			  	$(".biodiv", block).html(body.First).css("font-size", "small");
			  	var tbl = $("#roles", block);
			  	var gridimgpath = siteRoot + '/javascript/jQuery/jqGrid/themes/basic/images';

			  	tbl.jqGrid(
						{
							datatype: 'local',
							jsondata: body.Second,
							colNames: ['Title', 'Credit', 'Troupe'],
							imgpath: gridimgpath,
							colModel:
							[
								{ name: 'Title' },
								{ name: 'Credit' },
								{ name: 'Troupe' }
							]
						});
			  	tbl.css("font-size", "small");
			  	tbl.clearGridData();
			  	j.each(body.Second, function (pos) { tbl.addRowData(pos, this); });
			  }
			  );
		}
	});


	// ------------  ROLES ----------------------------------

	$("#autoRole").autocomplete(
	{
		source: AutoCompleteSource,
		url: siteRoot + "/Show/GetRolesText.rails",
		type: "text",
		extraParams: { prodid: function () { return j("#prodId").val(); }, limit: 20 },
		width: 168,
		mustMatch: false,
		autoFill: false,
		selectFirst: false
	});

	$("#btnAddRole").click(function (event) {
		$("#imgLoading").show();
		j.ajax({
			url: siteRoot + "/Admin/AddCastMember.rails",
			data:
			{
				prodid: j("#prodId").val(),
				person: personId,
				roleName: $("#autoRole").val()
			},
			dataType: 'json',
			success: function (body) {
				LoadCrewGrid(currentTab);
				//                $.growl("Role Saved: "+ $("#autoName").val() + " as " + $("#autoRole").val() + " saved");
				$('#StatusBar').jnotifyAddMessage({
					text: "Role Saved: " + $("#autoName").val() + " as " + $("#autoRole").val() + " saved",
					permanent: false,
					type: 'message'
				});

				$("#autoName").setFocus().select();
			},
			complete: function (xhr, status) {
				$("#imgLoading").hide();
			}
		});
	});

	// ------------  CREW CREDITS ----------------------------------

	var creditId = 0;

	$("#btnAddCredit").click(function (event) {
		if (currentTab == 1)
			creditId = $("#autoCredit").val();
		else
			creditId = $("#autoAuthor").val();

		if (creditId > 0) {
			$("#imgLoading").show();
			j.ajax({
				url: siteRoot + "/WS/AddCredit.rails",
				data:
				{
					prodid: j("#prodId").val(),
					person: personId,
					'credit': creditId,
					which: currentTab
				},
				dataType: 'json',
				success: function (body) {
					LoadCrewGrid(currentTab);
					$('#StatusBar').jnotifyAddMessage({
						text: "Credit Saved: " + $("#autoName").val(),
						permanent: false,
						type: 'message'
					});

					$("#autoName").setFocus().select();
				},
				complete: function (xhr, status) {
					$("#imgLoading").hide();
				}
			});
		}
	});
	$("#waiting").slideUp("slow");
	$("#wizard").slideDown("slow");


});

	function ShowProd(id) 
	{
		j("input[type='hidden']", j(this).parent()).val(id);
		j("#showPanel").show();
		j("#autoName").setFocus();
		j("#prodId").val(id);
		j("#hypShow").attr("href", siteRoot + "/Show/Display.rails?ID=" + id);

		InitCastGrid(0, 'tblCast', ['Delete', 'Person', 'Role']);
		InitCastGrid(1, 'tblCrew', ['Delete', 'Person', 'Credit']);
		InitCastGrid(2, 'tblAuthor', ['Delete', 'Person', 'Credit']);

		LoadCrewGrid(currentTab);
		j("#autoRole")
		.autocomplete("option", { extraParams: { prodId: j("#prodId").val()} })
		.val('');
		j.ajax({
			url: siteRoot + "/Admin/RecordCastList.rails",
			data: { id: j("#prodId").val() },
			dataType: 'json'
		});
	}

	//----------------------------------------------------------------------------------------------------
	function LoadCrewGrid(index) 
	{
		var tbls = ["#tblCast", "#tblCrew", "#tblAuthor"]
		j(tbls[index]).setGridParam({ datatype: 'json', postData: { prodId: j("#prodId").val()} }).trigger("reloadGrid");
	}
	//----------------------------------------------------------------------------------------------------
	function InitCastGrid(inx, id, colNames) 
	{
		var gridimgpath = siteRoot + '/javascript/jQuery/jqGrid/themes/basic/images';

		j("#" + id).jqGrid(
				{
					url: siteRoot + '/Show/GetCastJson.rails',
					postData: { prodId: j("#prodId").val(), which: inx },
					datatype: "clientSide",
					colNames: colNames,
					jsonReader: { repeatitems: false },
					colModel:
					[
						{ name: 'ID', hidden: true, key: true, jsonmap: 'ID' },
						{ name: 'Person', key: 'Person', width: 270 },
						{ name: 'Credit', key: 'Credit', width: 250 }
					],
					imgpath: gridimgpath,
					editurl: siteRoot + '/Admin/DeleteCast.rails?which=' + inx,
					pager: jQuery('#pager' + inx),
					sortname: 'Person',
					viewrecords: true,
					numRow: 15,
					sortorder: "asc",
					caption: colNames[2]
				}).navGrid('#pager' + inx, { edit: false, add: false, del: true },       // button options
						{}, // edit options
						{}, // add options
						{}  // del options
						);
	}
